package com.ts.api.http.receive.biz;

import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.id.IdUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.Assert;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.constant.api.ApiEnum;
import com.ts.api.common.context.ApiContext;
import com.ts.api.common.entity.ApiParameter;
import com.ts.api.common.util.ApiDictUtils;
import com.ts.api.exp.ApiMsgException;
import com.ts.api.http.receive.entity.apply.req.ApiReceiveApplyZhenHaoJie;
import com.ts.api.http.receive.entity.dataexchange.req.ApiReceiveDataExchangeZhenHaoJie;
import com.ts.api.module.api.convert.core.annotation.ApiReceive;
import com.ts.api.module.api.convert.core.annotation.ApiReceiveConvertType;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveApply;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveDecrypt;
import com.ts.api.module.api.convert.receive.entity.ApiReceiveNotice;
import com.ts.api.module.api.convert.receive.entity.ApiReceivePhoneMd5DataExchange;
import com.ts.api.module.api.convert.receive.handler.ApiReceivePhoneMd5ConvertHandler;
import com.ts.api.module.api.entity.ApiUserRequest;

import java.util.Map;

/**
 * e时代采臻好借
 *
 * 臻好借文档：https://doc.apipost.net/docs/33e0878c48ee000   密码：313310
 *
 * @author WJB
 */
@ApiReceive(apiClientId = "1876689499564429312",type = ApiReceiveConvertType.API_CHANNEL_PHONE_MD5)
public class ApiReceivePhoneMd5ZhenHaoJie implements ApiReceivePhoneMd5ConvertHandler {

    private static String KEY = "1LX6k13Ad7Iu0ykv";

    @Override
    public Map<String, String> requireParam(RequestVO requestVO) throws Exception {
        //  获取请求体参数
        Map<String, Object> map = JsonUtils.toMap(requestVO.getBody());

        //  传递什么，验证什么Key
        String content = String.valueOf(map.get("content"));
        String channelCode = String.valueOf(map.get("channelCode"));
        String serialNo = String.valueOf(map.get("serialNo"));

        Assert.isNotEmptyThrows(content, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("content")));
        Assert.isNotEmptyThrows(channelCode, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("channelCode")));
        Assert.isNotEmptyThrows(serialNo, new ApiMsgException(ApiEnum.API_RECEIVE_BODY_MISS.format("serialNo")));

        //  本次撞库/进件上下文参数
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        apiParameter.put("serialNo", serialNo);
        //  返回需要的数据Map
        return MapUtils.newHashMap(newMap -> {
            newMap.put("content", content);
            newMap.put("channelCode", channelCode);
            newMap.put("serialNo", serialNo);
        });
    }

    @Override
    public ApiReceiveDecrypt decrypt(Map<String, String> paramMap, RequestVO requestVO) throws Exception {
        String data = paramMap.get("content");

        //  文档解密过程
        AES ecb = AES.createEcb(KEY.getBytes());
        String decrypt = ecb.decryptFromBase64Str(data);
        return new ApiReceiveDecrypt(decrypt);
    }

    @Override
    public ApiUserRequest parseDataExchange(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveDataExchangeZhenHaoJie parse = apiReceiveDecrypt.parse(ApiReceiveDataExchangeZhenHaoJie.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respDataExchange(ApiReceivePhoneMd5DataExchange dataExchangeMessage) throws Exception {
        ApiParameter apiParameter = ApiContext.PARAMETER.get();
        boolean suc = dataExchangeMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("msg", dataExchangeMessage.getBizMsg());
            return resultMap;
        }

        //成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("serialNo", apiParameter.get("serialNo"));
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
            // 产品价格(CPS返回产品价格，CPA返回合作单价)
            dataMap.put("price", dataExchangeMessage.getPrice());
            // 产品折算后价格(CPS返回此折算价格字段，CPA模式无折算价格返回)
            dataMap.put("discountPrice", dataExchangeMessage.getChannelSharePrice());
            // 机构主体名称
            dataMap.put("companyName", dataExchangeMessage.getOrgName());
            // 机构logo
            dataMap.put("logo", dataExchangeMessage.getLogoPath());
            // 产品名称
            dataMap.put("productName", dataExchangeMessage.getDisplayName());
            // 用户每次撞库成功时唯一订单号，进件申请时需要
            dataMap.put("applyNo", IdUtils.getSimpleUuid());
            // 协议列表
            dataMap.put("protocolList", CollUtils.newArrayList(newList -> {
                Map<String, Object> protocol = MapUtils.newLinkedHashMap();
                // 协议名称
                protocol.put("protocolName", "个人信息授权协议");
                // 协议地址
                protocol.put("protocolUrl", "https://axh.rongyiudai.com/h5ViewProtocol?uniqueCode=1fc1379861b34ef0898d7864c33b18e2");
                newList.add(protocol);
            }));
        }));
        return resultMap;
    }

    @Override
    public ApiUserRequest parseApply(ApiReceiveDecrypt apiReceiveDecrypt) throws Exception {
        ApiReceiveApplyZhenHaoJie parse = apiReceiveDecrypt.parse(ApiReceiveApplyZhenHaoJie.class);
        ApiUserRequest apiUserRequest = CopyUtils.copy(parse, ApiUserRequest.class);
        fieldMapping(apiUserRequest);
        return apiUserRequest;
    }

    @Override
    public Map<String, Object> respApply(ApiReceiveApply applyMessage) throws Exception {
        boolean suc = applyMessage.hasBizSuc();

        // 失败
        if (!suc) {
            Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
            resultMap.put("code", 500);
            resultMap.put("msg", applyMessage.getBizMsg());
            return resultMap;
        }

        ApiParameter apiParameter = ApiContext.PARAMETER.get();

        // 成功
        Map<String, Object> resultMap = MapUtils.newLinkedHashMap();
        resultMap.put("code", 200);
        resultMap.put("msg", "操作成功");
        resultMap.put("data", MapUtils.newLinkedHashMap(dataMap -> {
        }));
        resultMap.put("serialNo", apiParameter.get("serialNo"));
        return resultMap;
    }

    @Override
    public void fieldMapping(ApiUserRequest apiUserRequest) {
        //  age 年龄
        String age = ApiDictUtils.convertAge(apiUserRequest.getAge());
        apiUserRequest.setAge(age);

        // sex 	性别 0-女 1-男 默认1
        // sex 性别
        // 0 男
        // 1 女
        String sex = apiUserRequest.getSex();
        if (ValidParam.isNotEmpty(sex)) {
            String sexChoose = ChooseEq.create()
                .when(sex, "0", "1")
                .when(sex, "1", "0")
            .end();
            apiUserRequest.setSex(sexChoose);
        }

        // 	芝麻分 1-无芝麻分 2-600分以下 3-600~650分 4-650~700分 5-700分以上 默认2
        // sesameCredit 芝麻分
        // 1 600分以下
        // 2 600~649分
        // 3 650~699分
        // 4 700分以上
        String sesameCredit = apiUserRequest.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "2", "1")
                    .when(sesameCredit, "3", "2")
                    .when(sesameCredit, "4", "3")
                    .when(sesameCredit, "5", "4")
                    .end();
            apiUserRequest.setSesameCredit(value);
        }

        // 公积金 1-无公积金 2-有公积金 默认1
        // providentFund 公积金
        // 1 无公积金
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有公积金
        String providentFund = apiUserRequest.getProvidentFund();
        if (ValidParam.isNotEmpty(providentFund)) {
            String value = ChooseEq.create()
                    .when(providentFund, "1", "1")
                    .when(providentFund, "2", "4")
                    .end();
            apiUserRequest.setProvidentFund(value);
        }

        // 社保 1-无社保 2-有社保 默认1
        // socialSecurity 社保缴纳
        // 1 无社保
        // 2 缴纳6个月以下
        // 3 缴纳6个月以上
        // 4 有社保
        String socialSecurity = apiUserRequest.getSocialSecurity();
        if (ValidParam.isNotEmpty(socialSecurity)) {
            String value = ChooseEq.create()
                    .when(socialSecurity, "1", "1")
                    .when(socialSecurity, "2", "4")
                    .end();
            apiUserRequest.setSocialSecurity(value);
        }

        // 保单（1-无；2-有）
        // insurancePolicy 保险保单
        // 1 无保险保单
        // 2 缴纳未满1年
        // 3 缴纳1年以上
        // 4 有保险保单
        String insurancePolicy = apiUserRequest.getInsurancePolicy();
        if (ValidParam.isNotEmpty(insurancePolicy)) {
            String value = ChooseEq.create()
                    .when(insurancePolicy, "1", "1")
                    .when(insurancePolicy, "2", "4")
                    .end();
            apiUserRequest.setInsurancePolicy(value);
        }

        // 	房产情况 1-无 2-有 默认1
        // realEstateInfo 房产情况
        // 1 无房产
        // 2 有房不抵押
        // 3 有房可抵押
        // 4 有房产
        // 5 有按揭房产
        // 6 有全款房产
        String realEstateInfo = apiUserRequest.getRealEstateInfo();
        if (ValidParam.isNotEmpty(realEstateInfo)) {
            String value = ChooseEq.create()
                    .when(realEstateInfo, "1", "1")
                    .when(realEstateInfo, "2", "4")
                    .end();
            apiUserRequest.setRealEstateInfo(value);
        }

        // 车辆信息（1-无；2-有）
        // carInfo 车辆情况
        // 1 无车产
        // 2 有车不抵押
        // 3 有车可抵押
        // 4 有车产
        String carInfo = apiUserRequest.getCarInfo();
        if (ValidParam.isNotEmpty(carInfo)) {
            String value = ChooseEq.create()
                    .when(carInfo, "1", "1")
                    .when(carInfo, "2", "4")
                    .end();
            apiUserRequest.setCarInfo(value);
        }

        // 职业身份 1-上班族 2-公务员/事业单位 3-私营业主 4-个体户 5-其他 默认1
        // career 职业
        // 1 上班族
        // 2 自由职业
        // 3 企业主（有营业执照）
        // 4 公务员或事业单位
        // 5 个体户
        String career = apiUserRequest.getCareer();
        if (ValidParam.isNotEmpty(career)) {
            String value = ChooseEq.create()
                .when(career, "1", "1")
                .when(career, "2", "4")
                .when(career, "3", "3")
                .when(career, "4", "5")
                .when(career, "5", "2")
                .end();
            apiUserRequest.setCareer(value);
        }

        // license 经营执照 1：没办理 2：已办理，注册满 1 年3：已办理，注册满 3 年 4：已办理，注册满 5 年以上 默认1 职业身份为3-私营业主 4-个体户时必填
        // 营业执照注册年限
        // 1 未注册
        // 2 注册1年以下
        // 3 注册1~5年
        // 4 注册5年以上
        String bizLicenseYear = apiUserRequest.getBizLicenseYear();
        if (ValidParam.isNotEmpty(bizLicenseYear)) {
            String value = ChooseEq.create()
                    .when(bizLicenseYear, "1", "1")
                    .when(bizLicenseYear, "2", "2")
                    .when(bizLicenseYear, "3", "3")
                    .when(bizLicenseYear, "4", "4")
                    .end();
            apiUserRequest.setBizLicenseYear(value);
        }

        // 借款金额（单位元 如：50000）
        String loanAmount = apiUserRequest.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String value = ApiDictUtils.convertLoanAmount(apiUserRequest.getLoanAmount(),true);
            apiUserRequest.setLoanAmount(value);
        }

        // 月收入 1：4000 以下 2：4000-8000 3：8000-1.5 万 4：1.5 万-2 万 5：2 万-3 万 6：3 万以上 默认2
        // 1 1000-3000
        // 2 3000-8000
        // 3 8000-15000
        // 4 15000-30000
        // 5 30000以上
        String monthlySalary = apiUserRequest.getMonthlySalary();
        if (ValidParam.isNotEmpty(monthlySalary)) {
            String value = ChooseEq.create()
                    .when(monthlySalary, "1", "1")
                    .when(monthlySalary, "2", "2")
                    .when(monthlySalary, "3", "3")
                    .when(monthlySalary, "4", "4")
                    .when(monthlySalary, "5", "4")
                    .when(monthlySalary, "6", "5")
                    .end();
            apiUserRequest.setMonthlySalary(value);
        }
    }


    @Override
    public Object reqPullApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPullApplyNotice(String responseBody) {
        return false;
    }

    @Override
    public Object reqPushApplyNotice(ApiReceiveNotice apiReceiveNotice) {
        return null;
    }

    @Override
    public boolean respPushApplyNotice(String responseBody) {
        return false;
    }


}
